package com.demo.auth.common.service;

import cn.dev33.satoken.stp.SaTokenInfo;
import cn.dev33.satoken.stp.StpUtil;
import com.demo.common.core.constants.Constants;
import com.demo.common.core.utils.ip.IpUtils;
import com.demo.common.log.manager.AsyncManager;
import com.demo.common.log.manager.factory.AsyncFactory;
import com.demo.common.redis.constants.CacheConstants;
import com.demo.common.redis.service.RedisService;
import com.demo.common.core.domain.LoginUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.concurrent.TimeUnit;


/**
 * token验证处理
 *
 * @author wr
 */
@Component
public class TokenService {

    @Autowired
    private RedisService redisService;

    @Value("${sa-token.timeout}")
    private long tokenTimeout;

    /**
     * 生成token
     *
     * @param loginUser
     * @return
     */
    public SaTokenInfo createToken(LoginUser loginUser) {
        loginUser.setLoginTime(System.currentTimeMillis());
        loginUser.setExpireTime(loginUser.getLoginTime() + tokenTimeout * 1000);
        String ip = IpUtils.getIpAddr();
        loginUser.setIpAddr(ip);
        loginUser.getSysUserBo().setLoginIp(ip);
        loginUser.getSysUserBo().setLoginDate(new Date());
        StpUtil.login(loginUser.getUserId());
        String userKey = CacheConstants.LOGIN_USER_KEY + loginUser.getUserId();
        redisService.setCacheObject(userKey, loginUser, tokenTimeout, TimeUnit.SECONDS);
        // 记录用户登录日志
        AsyncManager.me().execute(AsyncFactory.recordLogininfor(loginUser.getAk(), Constants.LOGIN_SUCCESS, "登录成功"));
        return StpUtil.getTokenInfo();
    }
}